<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/layout' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>邮件管理</el-breadcrumb-item>
      <el-breadcrumb-item>邮件模板</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片布局 -->
    <el-card>
      <!-- 植入搜索栏 -->
      <el-row :gutter="20">
        <el-col :span="5">
          <el-input clearable placeholder="邮件名称" v-model="searchName"></el-input>
        </el-col>
        <el-col :span="5">
          <el-input clearable placeholder="邮件明细" v-model="searchDetail"></el-input>
        </el-col>

        <el-col :span="2">
          <el-button type="primary" @click="getMailList()">
            <el-icon>
              <Search/>
            </el-icon>
          </el-button>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="showAddBox = true">上传邮件模板</el-button>
        </el-col>
      </el-row>
      <!-- 放入table -->
      <el-table
          :data="mails"
          style="width: 100%; height: 550px; margin-top:10px;"
          border
          :header-cell-style="{ height: '37px', padding: '0' }"
          :row-style="{ height: '37px' }"
          :cell-style="{ padding: '0' }"
      >
        <!-- 数据绑定 -->
        <el-table-column fixed label="邮件Id" width="80" prop="id"></el-table-column>
        <el-table-column label="模板名称" width="250" prop="name"></el-table-column>
        <el-table-column label="模板明细" width="300" prop="detail"></el-table-column>
        <el-table-column label="备注信息" width="300" prop="remark"></el-table-column>
        <el-table-column label="可用性" width="100" prop="enable"></el-table-column>
        <el-table-column label="是否锁定" width="100" prop="lockable"></el-table-column>
        <el-table-column label="上传者" width="80" prop="createBy"></el-table-column>
        <el-table-column label="上传时间" width="200" prop="createDate"></el-table-column>
        <el-table-column fixed="right" label="操作" width="300">
          <template #default="scope">
            <el-button size="small" type="primary" @click="showMail(scope.row)">查看明细</el-button>
            <el-button size="small" type="success" @click="showMailSend(scope.row)">群发邮件</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页模块 -->
      <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :small="false"
          :disabled="false"
          :background="true"
          layout="total, sizes, prev, pager, next"
          :total="totalCount"
          @size-change="onSizeChange"
          @current-change="onPageChange"
      />
      <!-- 添加会话框 -->
      <el-dialog title="上传邮件模板" v-model="showAddBox" width="30%" :before-close="clearEdit" style="padding: 8px 15px;"
                 @close="onClose">
        <el-form :model="mailDetail" label-width="120px">
          <el-form-item label="邮件明细" prop="name">
            <el-input v-model="mailDetail.detail"></el-input>
          </el-form-item>
          <el-form-item label="备注信息" prop="detail">
            <el-input v-model="mailDetail.remark"></el-input>
          </el-form-item>
        </el-form>
        <br>
        <el-divider>输入相关信息后，会与模板一并上传</el-divider>
        <br>
        <el-upload
            ref="uploadRef"
            accept=".html"
            class="upload-demo"
            drag
            :headers="uploadHeaders"
            :show-file-list="false"
            :before-upload="judgeType"
            :on-success="handleSuccess"
            :on-error="handleError"
            :disabled="uploading"
            :multiple="false"
            :limit="1"
            :http-request="uploadFile"
        >
          <el-icon>
            <upload-filled/>
          </el-icon>
          <div class="el-upload__text">
            将邮件模板<em>拖拽到此处</em>或 <em>点击</em>以进行上传
          </div>
          <template #tip>
            <div class="el-upload__tip">
              仅支持上传50MB以下的<em>html</em>文件
            </div>
          </template>
        </el-upload>
      </el-dialog>
      <!-- 修改会话框 -->
      <el-dialog title="修改定时任务" v-model="showEditBox" width="40%" :before-close="clearEdit" style="padding: 8px 15px;"
                 @close="onClose">
        <el-form :model="mailDetail" :rules="mailFromRules" ref="mailFromRules" label-width="120px">
          <el-form-item label="模板名称" prop="name">
            <el-input v-model="mailDetail.name"></el-input>
          </el-form-item>
          <el-form-item label="模板明细" prop="detail">
            <el-input v-model="mailDetail.detail"></el-input>
          </el-form-item>
          <el-form-item label="模板备注" prop="remark">
            <el-input v-model="mailDetail.remark"></el-input>
          </el-form-item>

          <el-form-item class="dialog-footer">
            <el-button @click="clearEdit">取消</el-button>
            <el-button type="primary" @click="handleEdit('jobFromRules')">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 查看模板 -->
      <el-dialog title="查看邮件模板明细" v-model="showModelBox" width="40%" :before-close="clearEdit"
                 style="padding: 8px 15px;" @close="onClose">
        <div v-html="dialogContent"></div>
      </el-dialog>

      <el-dialog title="选择需要发送邮件的用户" v-model="showToSendUser" width="40%" :before-close="clearEdit"
                 style="padding: 8px 15px;" @close="onClose">
        <em style="color: #3a3a3a">仅显示已注册邮箱的用户</em>
        <el-table row-key="id" ref="tableRef" :data="toUsers" style="width: 100%" height="500" default-expand-all
                  @selection-change="handleSelectionChange" tooltip-effect="dark">
          <el-table-column type="selection" :reserve-selection="true"/>
          <!-- 数据展示列 -->
          <el-table-column label="用户Id" width="100" prop="id"></el-table-column>
          <el-table-column label="用户名称" width="100" prop="username"></el-table-column>
          <el-table-column label="用户账号" width="150" prop="account"></el-table-column>
          <el-table-column label="用户邮箱" width="200" prop="email"></el-table-column>
          <el-table-column label="用户可用性" width="150" prop="enable"></el-table-column>
        </el-table>
        <div style="margin-top: 20px">
          <el-button type="info" @click="toggleSelection()">清空选择</el-button>
          <el-button type="primary" @click="changeEnable()">切换用户状态</el-button>
          <el-popover :visible="confirmSend" effect="top" trigger="hover" placement="top" width="auto" >
            <template #default>
              <div style="display: flex; align-items: center;">
                <el-input v-model="subject" placeholder="请输入邮件主题" :rules="[{ required: true, message: '邮件主题不能为空', trigger: 'blur' }]"></el-input>
                <el-button type="primary" @click="handleSend()">确定</el-button>
              </div>
            </template>
            <template #reference>
              <el-button type="primary" @click="confirmSend=true">确定</el-button>
            </template>
          </el-popover>

        </div>
      </el-dialog>
    </el-card>
  </div>
</template>


<script>
import {ElMessage} from 'element-plus';
import {getMailDetail, getMailList, uploadMail, sendMails, deleteMail} from "@/api/mail";
import {getUsersDontHasMail, getUsersHasMail} from '@/api/user'

export default {
  name: "mailList",
  data() {
    return {
      showAddBox: false,
      showEditBox: false,
      showModelBox: false,
      showToSendUser: false,
      judgeEnable: true,
      confirmSend:false,

      dialogContent: '',

      pageNo: 1,
      pageSize: 10,
      totalCount: 0,

      mails: [],
      mailDetail: [],
      toUsers: [],
      enableUsers: [],
      disableUsers: [],
      multipleSelection: [],
      mailName:'',
      subject:'',

      searchName: '',
      searchDetail: '',

      uploading: false,
      uploadPercentage: 0,

      // 如果需要设置请求头，可以在这里添加
      uploadHeaders: {
        'X-TOKEN': window.sessionStorage.getItem('token')
      },
    }
  },
  methods: {
    handleSelectionChange(val) {
      // 设置多选行数
      this.multipleSelection = val;
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.tableRef.toggleRowSelection(row);
        });
      } else {
        this.$refs.tableRef.clearSelection();
      }
    },
    handleSend() {
      //批量发送邮件
      console.log(this.multipleSelection)
      if (this.multipleSelection==[]||this.multipleSelection.length<=0){
        ElMessage.error("请选择需要发送邮件的用户！")
        return;
      }
      if (!this.subject){
        ElMessage.error("邮件主题不能为空！")
        return
      }
      const userMails = [];
      this.multipleSelection.forEach(item => {
        userMails.push(item.email)
      })
      const data={
        mails:userMails,
        mailName:this.mailName,
        subject:this.subject
      }
      console.log(data)
      sendMails(data).then(resp => {
        if (resp.success) {
          ElMessage.success("已发送邮件！")
          this.showToSendUser = false
          this.multipleSelection=[]
          this.$refs.tableRef.clearSelection();
        }
      })
    },
    uploadFile(content) {
      content.onSuccess();
    },
    onClose() {

      // 对话框关闭时重置上传状态
      this.uploading = false;
      this.uploadPercentage = 0;
      //关闭弹框
      this.showAddBox = false;
      this.showEditBox = false;
      this.showModelBox = false;
      this.confirmSend=false
      this.showToSendUser = false
    },
    clearEdit() {
      //清空表单默认值

      //关闭弹框
      this.confirmSend=false
      this.showAddBox = false;
      this.showEditBox = false;
      this.showModelBox = false;
      this.showToSendUser = false
    },

    onSizeChange(pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.getJobList();
    },
    onPageChange(page) {
      this.pageNo = page;
      this.getJobList();
    },
    judgeType(file) {
      const isHTML = file.type === 'text/html';
      const sizeLimit = file.size / 1024 / 1024 / 1024 < 50;
      if (!sizeLimit) {
        this.$message.error('上传文件大小不能超过 50MB!');
      }
      if (!isHTML) this.$message.error('请上传格式为 HTML 的文件！');
      return isHTML;
    },
    handleSuccess(response, file) {
      this.uploading = true;
      this.uploadPercentage = 0;
      var data = new FormData()
      data.append("file", file.raw)
      data.append("detail", this.mailDetail.detail)
      data.append("remark", this.mailDetail.remark)
      uploadMail(data).then(resp => {
        if (resp.success) {
          // 根据上传成功的响应处理逻辑
          this.$message.success('文件' + resp.data.filename + '已上传成功！');
          this.$refs['uploadRef'].clearFiles();
          this.uploading = false;
          this.showAddBox = false
          this.mailDetail = []
          this.getMailList()
        }
      })
    },
    handleError(error) {
      this.uploading = false;
      this.uploadPercentage = 0;
      this.$refs['uploadRef'].clearFiles();
      // 根据上传失败的响应处理逻辑
      this.$message.error('上传失败！');
    },
    getMailList() {
      this.searchStr = {
        name: this.searchName,
        detail: this.searchDetail
      };
      const param = {page: this.pageNo, limit: this.pageSize, searchStr: this.searchStr};
      getMailList(param).then(resp => {
        this.mails = resp.rows;
      });
    },
    showMail(row) {
      const param = {
        id: row.id,
        name: row.name
      }
      getMailDetail(param).then(resp => {
        if (resp.success) {
          this.showModelBox = true;
          this.dialogContent = resp.data.content
          ElMessage.success("已成功打开" + row.name)
        }
      })
    },
    showMailSend(row) {
      this.mailName=row.name
      this.showToSendUser = true
      getUsersDontHasMail().then(res => {
        this.disableUsers = res.rows
      })
    },
    handleDelete(index, row) {
      const data ={
        id:row.id
      }
      deleteMail(data).then(resp=>{
        if (resp.success){
          ElMessage.success("已删除序号为"+index+"的邮件")
        }
        this.getMailList()
        this.judgeEnable=true
      })
    },
    changeEnable() {
      this.judgeEnable = !this.judgeEnable
      if (this.judgeEnable) {
        this.toUsers = this.enableUsers
      } else {
        this.toUsers = this.disableUsers
      }
    }
  },
  mounted() {
    const param = {page: '', limit: ''};
    getMailList(param).then(resp => {
      this.mails = resp.rows;
    });
    getUsersHasMail().then(resp => {
      this.enableUsers = resp.rows
      this.toUsers = this.enableUsers
    })
  }
}
</script>

<style scoped>
div.el-breadcrumb {
  height: 45px;
}

.el-dialog__body {
  padding: 0px 15px;
}

.el-form-item {
  /* height: 68px; */
}
</style>